package com.example.newjiesai.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by SQ-1003530 on 2019/7/17.
 */
public class AesUtil {

    private static final String ENCODE="UTF-8";
    private  static String sKey="C544E974FCA2A884";

    private  static String iv="0102030405678912";

    /**
     * 加密
     *
     * @param sSrc 加密的明文
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc) throws Exception {
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv1 = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv1);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        return new BASE64Encoder().encode(encrypted);
    }

    /**
     * 解密
     * @param sSrc 接收到的加密过后的字符串（带解密密文）

     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc) throws Exception {
        try {
            //先用Base64解码
            byte[] byte1 = Base64.decode(sSrc);
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
            //与加密时不同MODE:Cipher.DECRYPT_MODE
            byte[] ret = cipher.doFinal(byte1);
            return new String(ret, ENCODE);
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

}
